<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>电子相册系统</title>
<link rel="stylesheet" href="/css/style.css">
<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<!-- 相册详细页面 -->
    <div id="albumDetailView" class="page">
    <header class="app-header">
        <div class="logo"><div class="mark">EA</div><div><div style="font-weight:800">电子相册</div><div class="muted" style="font-size:13px">分享 · 收藏 · 回忆</div></div></div>
        <button class="btn ghost" id="backToMainBtn" style="margin-left:auto;">返回主页面</button>
    </header>
    
    <main>
        <div class="album-detail-card" style="max-width:900px;margin:0 auto;display:flex;gap:32px;">
            <!-- 图片区 -->
            <div style="flex:2;min-width:0;">
                <div id="carousel" style="position:relative;width:100%;height:400px;overflow:hidden;background:#f6fbff;border-radius:16px;display:flex;align-items:center;justify-content:center;">
                    <button id="prevBtn" class="btn ghost" style="position:absolute;left:10px;top:50%;transform:translateY(-50%);z-index:2">‹</button>
                    <img id="carouselImg" src="" alt="相册图片" style="max-width:100%;max-height:380px;border-radius:12px;box-shadow:0 4px 16px #e6eef8;" />
                    <button id="nextBtn" class="btn ghost" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);z-index:2">›</button>
                </div>
                <div id="thumbList" style="display:flex;gap:8px;margin-top:16px;overflow-x:auto;"></div>
            </div>
            <!-- 信息区 -->
            <div style="flex:1;min-width:260px;">
                <h2 id="albumTitle">相册标题</h2>
                <div class="muted" id="albumMeta">创建者 | 创建时间 | 类别</div>
                <div style="margin:18px 0;display:flex;gap:12px;">
                    <button id="uploadBtn" class="btn ghost">相册管理</button>
                    <button id="backBtn" class="btn ghost">返回</button>
                </div>
                <div style="margin-top:18px;">
                    <h3>评论区</h3>
                    <div id="commentList" style="max-height:180px;overflow:auto;border-top:1px dashed #e6eef8;padding-top:8px;margin-bottom:8px;"></div>
                    <div style="display:flex;gap:8px;margin-top:8px;">
                        <input id="commentInput" placeholder="写评论..." style="flex:1;padding:10px;border-radius:8px;border:1px solid #eef6ff;" />
                        <button id="sendCommentBtn" class="btn" onclick="addComment()">发送</button>
                    </div>
                    <div style="margin-top:18px;display:flex;gap:12px;">
                        <button id="likeBtn" class="btn" onclick="changeLikeStatus()">👍 点赞</button>
                        <button id="favBtn" class="btn ghost" onclick="changeCollectionStatus()">⭐ 收藏</button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
    
        window.onload = function() {
            getAlbumInfo();
            getLikeStatus();
            getCollectionStatus();
            getCommentList();
            // 绑定“返回主页面”按钮
            document.getElementById('backToMainBtn').onclick = function() {
                window.location.href = '/main';
            };
            // 绑定“返回”按钮
            document.getElementById('backBtn').onclick = function() {
                window.history.back();
            };
        }

        function getAlbumId() {
            return window.location.pathname.split('/').pop();
        }
    // 相册信息实体
    const albumInfo = {
        title: "海边的夏天",
        author: "demo",
        created: "2025-11-28",
        category: "旅行",
        photos: [
            "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?q=80&w=1200&auto=format&fit=crop",
            "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?q=80&w=1200&auto=format&fit=crop",
            "https://images.unsplash.com/photo-1465101046530-73398c7f28ca?q=80&w=1200&auto=format&fit=crop"
        ]
    };
    // 评论区与点赞收藏实体
    const albumStatus = {
        liked: false,
        favorited: false,
        comments: [
            {user: "星光熠熠", text: "美极了", ts: "4小时前"},
            {user: "暮光闪闪", text: "我真没招了", ts: "2小时前"},
            {user: "塞拉斯蒂娅公主", text: "罒ω罒", ts: "1天前"}
        ]
    };
    function getAlbumInfo() {
        // 获取相册基本信息
        const albumId = window.location.pathname.split('/').pop();
        // 在控制台打印albumId以供调试
        console.log("获取相册信息ID:", albumId);
        fetch(`/getalbuminfo/${albumId}`)
          .then(res => res.json())
          .then(data => {
            console.log("相册信息数据:", data);
            Object.assign(albumInfo, data);
            renderAlbumDetail();
            showManageBtnIfAuthor();
          });
    }
    // 分别获取点赞、收藏、评论状态
    function getLikeStatus() {
        const albumId = window.location.pathname.split('/').pop();
        fetch('/getlike', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: albumId })
        })
        .then(res => res.json())
        .then(data => {
            albumStatus.liked = !!data.liked;
            console.log("点赞状态:", albumStatus.liked);
            updateLikeFavBtn();
        });
    }
    function changeLikeStatus() {
        const albumId = window.location.pathname.split('/').pop();
        console.log("切换点赞状态，当前状态:", albumStatus.liked);
        fetch('/changelike', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: albumId, liked: albumStatus.liked })
        });
        albumStatus.liked = !albumStatus.liked;
        updateLikeFavBtn();
    }


    function getCollectionStatus() {
        fetch('/getcollection', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: getAlbumId() })
        })
        .then(res => res.json())
        .then(data => {
            console.log("收藏状态数据:", data);
            albumStatus.favorited = !!data.collected;
            updateLikeFavBtn();
        });
    }

    function changeCollectionStatus() {
        fetch('/changecollection', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: getAlbumId(), favorited: albumStatus.favorited })
        });
        albumStatus.favorited = !albumStatus.favorited;
        updateLikeFavBtn();
    }

    function getCommentList() {
        fetch('/getcomments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: getAlbumId() })
        })
        .then(res => res.json())
        .then(data => {
            albumStatus.comments = Array.isArray(data.comments) ? data.comments : [];
            renderAlbumDetail();
        });
    }

    function addComment(text) {
        text = document.getElementById('commentInput').value.trim();
        if (!text) return alert('评论内容不能为空');
        fetch('/addcomment', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ albumId: getAlbumId(), text: text })
        }).then(() => {
            setTimeout(getCommentList, 500);
        });
        
    }





    let currentPhoto = 0;

    // helper: 支持后端新格式 {photoId, fileUrl} 或 旧格式 string
    function resolvePhotoUrl(p) {
        return (typeof p === 'string') ? p : (p && p.fileUrl) ? p.fileUrl : '';
    }
    function resolvePhotoId(p) {
        return (typeof p === 'string') ? null : (p && p.photoId) ? p.photoId : null;
    }

    function renderAlbumDetail() {
        document.getElementById('albumTitle').textContent = albumInfo.title;
        document.getElementById('albumMeta').textContent = `${albumInfo.author} | ${albumInfo.created} | ${albumInfo.category}`;
        // 轮播图
        updateCarousel();
        // 缩略图
        const thumbList = document.getElementById('thumbList');
        thumbList.innerHTML = '';
        (albumInfo.photos || []).forEach((p, idx) => {
            const url = resolvePhotoUrl(p);
            const id = resolvePhotoId(p);
            const img = document.createElement('img');
            img.src = url ? (url + '?t=' + Date.now()) : '';
            img.dataset.photoId = id || '';
            img.className = 'album-thumb' + (idx === currentPhoto ? ' selected-thumb' : '');
            img.style = `width:60px;height:44px;object-fit:cover;border-radius:8px;cursor:pointer;box-shadow:0 2px 8px #e6eef8;${idx===currentPhoto?'border:2px solid #2196f3;':''}`;
            img.onclick = () => { currentPhoto = idx; updateCarousel(); renderAlbumDetail(); };
            thumbList.appendChild(img);
        });
        // 评论区
        const commentList = document.getElementById('commentList');
        commentList.innerHTML = '';
        albumStatus.comments.forEach(c => {
            const div = document.createElement('div');
            div.style = 'padding:8px 0;border-bottom:1px dashed #e6eef8;';
            div.innerHTML = `<strong>${c.user}</strong><div class='muted' style='font-size:13px;margin-top:4px;'>${c.text}</div><div class='muted' style='font-size:11px;'>${c.ts}</div>`;
            commentList.appendChild(div);
        });
    }
    function updateCarousel() {
        const p = (albumInfo.photos || [])[currentPhoto];
        const url = resolvePhotoUrl(p);
        const id = resolvePhotoId(p);
        const carouselImg = document.getElementById('carouselImg');
        carouselImg.src = url ? (url + '?t=' + Date.now()) : '';
        carouselImg.dataset.photoId = id || '';
    }
    document.getElementById('prevBtn').onclick = function() {
        currentPhoto = (currentPhoto - 1 + albumInfo.photos.length) % albumInfo.photos.length;
        updateCarousel();
        renderAlbumDetail();
    };
    document.getElementById('nextBtn').onclick = function() {
        currentPhoto = (currentPhoto + 1) % albumInfo.photos.length;
        updateCarousel();
        renderAlbumDetail();
    };

    function updateLikeFavBtn() {
        document.getElementById('likeBtn').classList.toggle('ghost', !albumStatus.liked);
        document.getElementById('likeBtn').textContent = albumStatus.liked ? '👍 已点赞' : '👍 点赞';
        document.getElementById('favBtn').classList.toggle('ghost', !albumStatus.favorited);
        document.getElementById('favBtn').textContent = albumStatus.favorited ? '⭐ 已收藏' : '⭐ 收藏';
    }
        document.getElementById('uploadBtn').onclick = function() {
            const albumId = window.location.pathname.split('/').pop();
            window.location.href = `/albummanagement/${albumId}`;
        };

        // 根据当前用户是否为作者显示管理按钮
        function showManageBtnIfAuthor() {
                fetch('/getuserinfo')
                    .then(res => res.json())
                    .then(data => {
                        // 判断当前用户是否为作者
                        if (albumInfo.author === data.username) {
                            document.getElementById('uploadBtn').style.display = '';
                        } else {
                            document.getElementById('uploadBtn').style.display = 'none';
                        }
                    });
        }
    document.getElementById('backBtn').onclick = function() {
        window.location.href = '/main';
    };
    // 页面初始化时分别获取信息和状态
    getAlbumInfo();
    // 在渲染相册详情后判断管理按钮显示
    // 需在 renderAlbumDetail 后调用
    // 可在 getAlbumInfo 的 then(data=>...)里加 showManageBtnIfAuthor();
    </script>
</body>
</html>


